package com.ray.tool.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.TimeUnit;

/**
 * 使用ThreadPoolExecutor自定义线程池
 *
 * @author LiaoYuXing-Ray
 * @version 1.0
 * @createDate 2023/8/31 9:17
 * @see RayThreadFactory
 **/
public class RayThreadPool {
    private RayThreadPool() {

    }

    public static ThreadPoolExecutor fixedThreadPool() {
        return fixedThreadPool(null);
    }

    /**
     * 线程池创建
     * 默认保证CPU核数两杯的线程存活，设置最大上限
     * 即使对性能要求很多，资源占用很大也要保证每个任务及时送达，设置上限过小将会导致任务排队
     *
     * @return java.util.concurrent.ThreadPoolExecutor
     * @author LiaoYuXing-Ray 2023/10/7 15:58
     **/
    public static ThreadPoolExecutor fixedThreadPool(String prefix) {
        int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;
        int maximumPoolSize = Runtime.getRuntime().availableProcessors() * 4;
        return fixedThreadPool(prefix, corePoolSize, maximumPoolSize, 20L);
    }


    public static ThreadPoolExecutor fixedThreadPool(int corePoolSize, int maximumPoolSize) {
        return fixedThreadPool(null, corePoolSize, maximumPoolSize, 20L);
    }

    public static ThreadPoolExecutor fixedThreadPool(String prefix, int corePoolSize, int maximumPoolSize) {
        return fixedThreadPool(prefix, corePoolSize, maximumPoolSize, 20L);
    }

    /**
     * 线程池构造
     *
     * @param prefix          新线程命名的前缀-结合{@link RayThreadFactory} 可为空，设置了默认前缀
     * @param corePoolSize    核心线程数
     * @param maximumPoolSize 最大线程数
     * @param keepAliveTime   空闲线程等待新任务的最长时间（单位：秒）
     * @return java.util.concurrent.ThreadPoolExecutor
     * @author LiaoYuXing-Ray 2023/10/7 11:52
     **/
    public static ThreadPoolExecutor fixedThreadPool(String prefix, int corePoolSize, int maximumPoolSize, long keepAliveTime) {
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new RayThreadFactory(prefix), new AbortPolicy());
    }


}
